import babel from 'rollup-plugin-babel'
import postcss from 'rollup-plugin-postcss' //处理 CSS
import terser from '@rollup/plugin-terser' //压缩 UMD 规范的输出文件
import commonjs from '@rollup/plugin-commonjs' //处理 CommonJS
import typescript from '@rollup/plugin-typescript'  //其中，@rollup/plugin-typescript 插件会先从 tsconfig.json 中加载所有配置项作为其初始值。传递新的配置可以覆盖这些选项。你也可以设置 tsconfig 的值为文件路径来指定配置文件。
import resolve from '@rollup/plugin-node-resolve' //处理路径
import json from '@rollup/plugin-json'
import serve from 'rollup-plugin-serve'
import livereload from 'rollup-plugin-livereload';
import nodePolyfills from 'rollup-plugin-polyfill-node';
// import pkg from './package.json' assert { type: 'json' };
// import copy from 'rollup-plugin-copy'; 
const isProduction = process.env.NODE_ENV === 'production'
const pluginsWithEnv = isProduction ? [] : [serve({
  open: true,
  openPage: "/base/",
  port: 10008,
  contentBase: ['dist', 'examples'], // 加载对应文件夹下的静态资源 比如dist文件夹下的内容和examples文件夹下的内容都放在了一个资源包下
}), livereload('dist/main.cjs.js')]

const outPath = {
  main:'main.cjs.js',
  module:"index.esm.js",
  browser:'index.umd.js'
}
const pathResolve = function (path) {
  return path
};
const jobs = {
  cjs: {
    output: {
      dir: 'dist',
      format: 'cjs',
      entryFileNames: pathResolve(outPath.main),
    }

  },
  esm: {
    output: {
      dir: 'dist',
      format: 'esm',
      entryFileNames: pathResolve(outPath.module),
      sourcemap: false, // 是否输出sourcemap
    }

  },
  umd: {
    output: {
      dir: 'dist',
      format: 'umd',
      entryFileNames: pathResolve(outPath.browser),
      name: '$utils', // umd 模块名称，相当于一个命名空间，会自动挂载到window下面
      sourcemap: false,
      // @ts-ignore
      plugins: [terser()],
    },
  },
}

//调试默认umd
let mergeConfig = [];
if (process.env.BUILD_ENV) {
  mergeConfig = jobs[process.env.BUILD_ENV].output;
} else {
  Object.entries(jobs).forEach(([key, value]) => {
    mergeConfig.push(value.output)
  })
}
export default {
  input: './main.ts',
  output: mergeConfig,
  plugins: [
    json(),
    postcss({
      minimize: true,
      extensions: ['.css'],
      extract: true,
    }),
    resolve(),
    commonjs(),
    typescript({
      tsconfig: './tsconfig.json',
      compilerOptions: {
        incremental: false,
      },
    }),
    // copy({  
    //   targets: [  
    //     { src: 'package.json', dest: 'dist' }  
    //   ]  
    // }),
    babel({
      presets: ['@babel/preset-env'],
      exclude: 'node_modules/**',
      babelHelpers: 'bundled'
    }),
    nodePolyfills(),
    ...pluginsWithEnv
  ],
}
